package com.example.sendmessage.common;

import java.io.*;

/**
 * 序列化工具，将对象序列化成字节数组
 * 数组序列化成对象
 */
public class BinaryTool {
    /**
     * 将对象转换成字节数组
     * @param object 任何类
     * @return 转换的字节数组
     * @throws IOException 转换过程中异常
     */
    public static byte[] toBytes(Object object) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 将字节数组转换成对象
     * @param data 字节数组
     * @return 转换的对象
     * @throws IOException 字节数组流异常
     * @throws ClassNotFoundException object流异常
     */
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                object = objectInputStream.readObject();
            }
        }
        return object;
    }
}
